<template>
  <div class="h100" @click="closeSetting">
    <!-- 非全屏 start -->
    <div class="no-full" v-show="!isFullscreen">
      <transition name="fade">
        <small class="header-next clearfix" v-if="showWarningInfo && !obAccessKey">{{$t('dashboard.no_hash_info')}}<span class="pointer p-span" @click="toSetWarning">{{$t('dashboard.no_hash_btn')}}>></span><i @click="showWarningInfo = false;" class="fr icon iconfont icon-close pointer"></i></small>
      </transition>
      <div class="w">
        <!-- 面包屑 start -->
        <div class="dashboard-title clearfix">
          <Breadcrumb class="fl" :breadcrumbs="breadcrumbs" />
          <!-- <button @click="toFullScreen" class="fr full-btn">{{$t('dashboard.full_screen')}}</button> -->
        </div>
        <!-- 面包屑 end -->
        <!-- 顶部 start -->
        <div class="panel-top">
          <div class="item-title clearfix">
            <div class="name fl">{{$t('dashboard.real_data')}}</div>
            <div class="button-box fr">
              <button :class="{active:showData}" @click="showData = true;">{{$t('dashboard.show')}}</button>
              <button :class="{active:!showData}" @click="showData = false;">{{$t('dashboard.hide')}}</button>
            </div>
          </div>
          <div class="item-content">
            <div class="item">
              <div class="item-top">
                <spinner v-if="loading.workStats_init_loading" />
                <template v-else>
                  <cu class="val" v-show="showData" :val="shares_30m | num" :decimals="2"></cu>
                  <span class="val" v-show="!showData">**********</span>
                  <span class="unit">{{shares_30m_unit}}/s</span>
                </template>
              </div>
              <div class="item-bottom">
                <span class="name">{{$t('dashboard.real_force')}}</span>
              </div>
            </div>
            <div class="item">
              <div class="item-top">
                <spinner v-if="loading.workStats_init_loading" />
                <template v-else>
                  <cu class="val" v-show="showData" :val="active_count | num" :decimals="0"></cu>
                  <span class="val" v-show="!showData">**********</span>
                  <span class="unit">{{$t('unit.station')}}</span>
                </template>
              </div>
              <div class="item-bottom">
                <span class="name">{{$t('dashboard.workers_active')}}</span>
              </div>
            </div>
            <div class="item">
              <div class="item-top">
                <spinner v-if="loading.workStats_init_loading" />
                <template v-else>
                  <cu class="val" v-show="showData" :val="today_income | num" :decimals="incomeDecimal"></cu>
                  <span class="val" v-show="!showData">**********</span>
                  <span class="unit">{{coin_type_up}}</span>
                </template>
              </div>
              <div class="item-bottom">
                <span class="name">{{$t('dashboard.paymentInfoData_per')}}</span>
              </div>
            </div>
          </div>
        </div>
        <!-- 顶部 end -->
        <!-- 算力 start -->
        <div class="panel-item clearfix">
          <div class="item fl">
            <div class="item-title clearfix">
              <span class="name fl">{{$t('home.force')}}</span>
            </div>
            <div class="item-content">
              <table class="item-table suanli-table">
                <tr>
                  <th>
                    <div class="td-cell">
                      <span>{{ (subCoinType === 'dcr' || subCoinType === 'zec') ? $t('dashboard.minutes_15') : $t('dashboard.minutes_30')}}</span>
                    </div>
                  </th>
                  <td>
                    <div class="td-cell">
                      <spinner v-if="loading.workStats_init_loading" />
                      <template v-else>
                        <cu class="val" :val="shares_30m | num" :decimals="2"></cu>
                        <span class="unit">{{shares_30m_unit}}/s</span>
                      </template>
                    </div>
                  </td>
                </tr>
                <tr>
                  <th>
                    <div class="td-cell">
                      <span>{{ (subCoinType === 'dcr' || subCoinType === 'zec') ? $t('dashboard.one_houer') : $t('dashboard.hour_3')}}</span>
                    </div>
                  </th>
                  <td>
                    <div class="td-cell">
                      <spinner v-if="loading.workStats_init_loading" />
                      <template v-else>
                        <cu class="val" :val="shares_3h | num" :decimals="2"></cu>
                        <span class="unit">{{shares_3h_unit}}/s</span>
                      </template>
                    </div>
                  </td>
                </tr>
                <tr v-if="(subCoinType === 'dcr' || subCoinType === 'zec')">
                  <th>
                    <div class="td-cell">
                      <span>{{$t('dashboard.hour_24')}}</span>
                    </div>
                  </th>
                  <td>
                    <div class="td-cell">
                      <spinner v-if="loading.workStats_init_loading" />
                      <template v-else>
                        <cu class="val" :val="shares_24h | num" :decimals="2"></cu>
                        <span class="unit">{{shares_24h_unit}}/s</span>
                      </template>
                    </div>
                  </td>
                </tr>
                <tr v-show="!suanli_is_setting">
                  <th>
                    <div class="td-cell">
                      <span>{{$t('dashboard.hash_rate1')}}</span>
                      <button v-if="!obAccessKey" class="setting" @click.stop="suanli_is_setting=true;set_asset.hash_rate=asset.share;set_asset.unit=asset.unit">{{$t('dashboard.set')}}</button>
                    </div>
                  </th>
                  <td>
                    <div class="td-cell">
                      <spinner v-if="loading.get_subaccount_asset_loading" />
                      <template v-else>
                        <cu class="val" :val="asset.share | num" :decimals="2"></cu>
                        <span class="unit">{{asset.unit}}{{coinHashUnit}}/s</span>
                      </template>
                    </div>
                  </td>
                </tr>
                <tr v-show="suanli_is_setting">
                  <td colspan="2" class="setting-td">
                    <div class="td-cell input-td-cell" @click.stop>
                      <div class="input-box clearfix">
                        <input class="fl input-box_input" v-model="set_asset.hash_rate" type="text" :disabled="loading.set_subaccount_asset_share_loading" :placeholder="$t('dashboard.hash_rate_input')"
                        @keyup.enter="setSubaccountAsset(2)">
                        <el-select :disabled="loading.set_subaccount_asset_share_loading" class="dashboard-select fl" v-model="set_asset.unit" :placeholder="$t('dashboard.selector')">
                          <el-option v-for="(v,k) in suanli_unit_list" :key="k" :label="k" :value="k">
                          </el-option>
                        </el-select>
                        <button :disabled="loading.set_subaccount_asset_share_loading" class="fr" @click="setSubaccountAsset(2)">
                          <template v-if="!loading.set_subaccount_asset_share_loading">{{$t('btn.save')}}</template>
                          <i v-else class="el-icon-loading"></i>
                        </button>
                      </div>
                    </div>
                  </td>
                </tr>
                <tr>
                  <th>
                    <div class="td-cell"></div>
                  </th>
                  <td>
                    <div class="td-cell"></div>
                  </td>
                </tr>
              </table>
            </div>
          </div>
          <div class="item fr">
            <div class="item-title clearfix">
              <span class="name fl">{{$t('dashboard.calculation_curve')}}</span>
              <div class="button-box fr" v-if="!noMill || hasIncome">
                <button :class="{active:suanLi_dimension==='1h'}" :disabled="suanLi_dimension==='1h'||loading.subaccountHistory_init_loading" @click="suanLi_dimension = '1h';loading.subaccountHistory_init_loading=true;">{{$t('unit.hour')}}</button>
                <button :class="{active:suanLi_dimension==='1d'}" :disabled="suanLi_dimension==='1d'||loading.subaccountHistory_init_loading" @click="suanLi_dimension = '1d';loading.subaccountHistory_init_loading=true;">{{$t('unit.day')}}</button>
              </div>
            </div>
            <div class="item-content" v-loading="loading.subaccountHistory_init_loading" :element-loading-text="$t('unit.loading')">
              <echarts class="dashboard-echarts" ref="suanli_noFull_echarts" :option="suanLiEchartsOption" v-if="!noMill || hasIncome" />
              <div v-else class="noData">
                <p>{{$t('dashboard.no_mill')}}</p>
                <a target="_blank" :href="helpHref">{{$t('dashboard.add_mill')}} >></a>
              </div>
            </div>
          </div>
        </div>
        <!-- 算力 end -->
        <!-- 矿机 start -->
        <div class="panel-item clearfix">
          <div class="item fl">
            <div class="item-title clearfix">
              <span class="name fl">{{$t('dashboard.minging_machine')}}</span>
              <router-link class="link fr" to="/pools/mill">{{$t('dashboard.minging_machine_detail')}}</router-link>
            </div>
            <div class="item-content">
              <table class="item-table kuangji-table">
                <tr>
                  <th>
                    <div class="td-cell">
                      <span>{{$t('dashboard.active')}}</span>
                    </div>
                  </th>
                  <td>
                    <div class="td-cell">
                      <spinner v-if="loading.workStats_init_loading" />
                      <cu v-else class="val" :val="active_count | num" :decimals="0"></cu>
                    </div>
                  </td>
                </tr>
                <tr v-if="(subCoinType === 'dcr' || subCoinType === 'zec')">
                  <th>
                    <div class="td-cell">
                      <span>{{$t('dashboard.inactive')}}</span>
                    </div>
                  </th>
                  <td>
                    <div class="td-cell">
                      <spinner v-if="loading.workStats_init_loading" />
                      <cu v-else class="val" :val="inactive_count | num" :decimals="0"></cu>
                    </div>
                  </td>
                </tr>
                <tr>
                  <th>
                    <div class="td-cell">
                      <span>{{$t('dashboard.invalid')}}</span>
                    </div>
                  </th>
                  <td>
                    <div class="td-cell">
                      <spinner v-if="loading.workStats_init_loading" />
                      <cu v-else class="val" :val="dead_count | num" :decimals="0"></cu>
                    </div>
                  </td>
                </tr>
                <tr v-show="!kuangji_is_setting">
                  <th>
                    <div class="td-cell">
                      <span>{{$t('dashboard.mining_machine_assets')}}</span>
                      <button v-if="!obAccessKey" class="setting" @click.stop="kuangji_is_setting=true;set_asset.worker_num=asset.worker_num;">{{$t('dashboard.set')}}</button>
                    </div>
                  </th>
                  <td>
                    <div class="td-cell">
                      <spinner v-if="loading.get_subaccount_asset_loading" />
                      <template v-else>
                        <cu class="val" :val="asset.worker_num | num" :decimals="0"></cu>
                      </template>
                    </div>
                  </td>
                </tr>
                <tr v-show="kuangji_is_setting">
                  <td colspan="2" class="setting-td">
                    <div class="td-cell input-td-cell" @click.stop>
                      <div class="input-box clearfix">
                        <input :disabled="loading.set_subaccount_asset_worker_loading" class="fl kuangji_input input-box_input" v-model="set_asset.worker_num" type="text" :placeholder="$t('dashboard.mining_info')" @keyup.enter="setSubaccountAsset(1)">
                        <button :disabled="loading.set_subaccount_asset_worker_loading" class="fr" @click="setSubaccountAsset(1)">
                          <template v-if="!loading.set_subaccount_asset_worker_loading">{{$t('btn.save')}}</template>
                          <i v-else class="el-icon-loading"></i>
                        </button>
                      </div>
                    </div>
                  </td>
                </tr>
                <tr>
                  <th>
                    <div class="td-cell"></div>
                  </th>
                  <td>
                    <div class="td-cell"></div>
                  </td>
                </tr>
              </table>
            </div>
          </div>
          <div class="item fr">
            <div class="item-title clearfix">
              <span class="name fl">{{$t('dashboard.minging_curve')}}</span>
              <div class="button-box fr" v-if="!noMill || hasIncome">
                <button :class="{active:kuangji_dimension==='1h'}" :disabled="kuangji_dimension==='1h'||loading.getWorkerStas_init_loading" @click="kuangji_dimension = '1h';loading.getWorkerStas_init_loading=true;">{{$t('unit.hour')}}</button>
                <button :class="{active:kuangji_dimension==='1d'}" :disabled="kuangji_dimension==='1d'||loading.getWorkerStas_init_loading" @click="kuangji_dimension = '1d';loading.getWorkerStas_init_loading=true;">{{$t('unit.day')}}</button>
              </div>
            </div>
            <div class="item-content" v-loading="loading.getWorkerStas_init_loading" :element-loading-text="$t('unit.loading')">
              <echarts class="dashboard-echarts" ref="kuangji_noFull_echarts" :option="kuangJiEchartsOption" v-if="!noMill || hasIncome" />
              <div v-else class="noData">
                <p>{{$t('dashboard.no_mill2')}}</p>
                <a target="_blank" :href="helpHref">{{$t('dashboard.add_mill')}} >></a>
              </div>
            </div>
          </div>
        </div>
        <!-- 矿机 end -->
        <!-- 收益 start -->
        <div class="panel-item clearfix">
          <div class="item fl">
            <div class="item-title clearfix">
              <span class="name fl">{{$t('dashboard.income')}}</span>
              <router-link class="link fr" to="/pools/income">{{$t('dashboard.income_detail')}}</router-link>
            </div>
            <div class="item-content">
              <table class="item-table shouyi-table">
                <tr>
                  <th>
                    <div class="td-cell">
                      <span>{{$t('dashboard.total_income')}}</span>
                    </div>
                  </th>
                  <td>
                    <div class="td-cell">
                      <spinner v-if="loading.workStats_init_loading" />
                      <template v-else>
                        <cu class="val" :val="sum_income | num" :decimals="incomeDecimal"></cu>
                        <span class="unit">{{coin_type_up}}</span>
                      </template>
                    </div>
                  </td>
                </tr>
                <tr>
                  <th>
                    <div class="td-cell">
                      <span>{{$t('dashboard.yesterdayearn')}}</span>
                    </div>
                  </th>
                  <td>
                    <div class="td-cell">
                      <spinner v-if="loading.workStats_init_loading" />
                      <template v-else>
                        <cu class="val" :val="net_income | num" :decimals="incomeDecimal"></cu>
                        <span class="unit">{{coin_type_up}}</span>
                      </template>
                    </div>
                  </td>
                </tr>
                <tr>
                  <th>
                    <div class="td-cell">
                      <span>{{$t('dashboard.pay_amount')}}</span>
                    </div>
                  </th>
                  <td>
                    <div class="td-cell">
                      <spinner v-if="loading.workStats_init_loading" />
                      <template v-else>
                        <cu class="val" :val="pay_income | num" :decimals="incomeDecimal"></cu>
                        <span class="unit">{{coin_type_up}}</span>
                      </template>
                    </div>
                  </td>
                </tr>
                <tr>
                  <th>
                    <div class="td-cell">
                      <span>{{$t('dashboard.earn')}}</span>
                    </div>
                  </th>
                  <td>
                    <div class="td-cell">
                      <spinner v-if="loading.workStats_init_loading" />
                      <template v-else>
                        <cu class="val" :val="not_pay_income | num" :decimals="incomeDecimal"></cu>
                        <span class="unit">{{coin_type_up}}</span>
                      </template>
                    </div>
                  </td>
                </tr>
              </table>
            </div>
          </div>
          <div class="item fr">
            <div class="item-title clearfix">
              <span class="name fl">{{$t('dashboard.income_curve')}}</span>
              <div class="button-box fr" v-if="!noMill || hasIncome">
                <button :class="{active:paymentHistoryLimit===7}" :disabled="paymentHistoryLimit===7||loading.paymentHistory_init_loading" @click="paymentHistoryLimit = 7;loading.paymentHistory_init_loading = true;">{{$t('unit.week')}}</button>
                <button :class="{active:paymentHistoryLimit===30}" :disabled="paymentHistoryLimit===30||loading.paymentHistory_init_loading" @click="paymentHistoryLimit = 30;
                loading.paymentHistory_init_loading = true;">{{$t('unit.month')}}</button>
              </div>
            </div>
            <div class="item-content" v-loading="loading.paymentHistory_init_loading" :element-loading-text="$t('unit.loading')">
              <echarts class="dashboard-echarts" ref="shouyi-echarts" :option="shouyiOption" v-if="!noMill || hasIncome" />
              <div v-else class="noData">
                <p>{{$t('dashboard.no_mill3')}}</p>
                <a target="_blank" :href="helpHref">{{$t('dashboard.add_mill')}} >></a>
              </div>
            </div>
          </div>
        </div>
        <!-- 收益 end -->
        <!-- 底部列表 start -->
        <div class="panel-bottom clearfix">
          <div v-loading="loading.activeWorkerList_loading" :element-loading-text="$t('unit.loading')" class="item fl">
            <div class="item-title clearfix">
              <span class="name fl">{{$t('dashboard.new_dynamic')}}</span>
            </div>
            <div class="item-content">
              <table class="item-table">
                <thead>
                  <tr>
                    <th>
                      <div class="td-cell">
                        <span>{{$t('dashboard.time')}}</span>
                      </div>
                    </th>
                    <th>
                      <div class="td-cell">
                        <span>{{$t('dashboard.minging_machine')}}</span>
                      </div>
                    </th>
                    <th>
                      <div class="td-cell">
                        <span>{{$t('dashboard.now_rate')}}</span>
                      </div>
                    </th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(v,k) in active_workers" :key="k">
                    <td>
                      <div class="td-cell">
                        <span>{{v.last_share_time}}</span>
                      </div>
                    </td>
                    <td>
                      <div class="td-cell">
                        <span>{{v.worker_name}}</span>
                      </div>
                    </td>
                    <td>
                      <div class="td-cell">
                        <span>{{v.accept_15m}}</span>
                      </div>
                    </td>
                  </tr>
                  <tr v-if="!active_workers.length">
                    <td colspan="3">
                      <div class="td-cell">
                        <p>{{$t('unit.no_data')}}</p>
                      </div>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
          <div v-loading="loading.inActiveWorkerList_loading" :element-loading-text="$t('unit.loading')" class="item fr">
            <div class="item-title clearfix">
              <span class="name fl">{{$t('dashboard.no_new_dynamic')}}</span>
            </div>
            <div class="item-content">
              <table class="item-table">
                <thead>
                  <tr>
                    <th>
                      <div class="td-cell">
                        <span>{{$t('dashboard.last_commit_time')}}</span>
                      </div>
                    </th>
                    <th>
                      <div class="td-cell">
                        <span>{{$t('dashboard.minging_machine')}}</span>
                      </div>
                    </th>
                    <th>
                      <div class="td-cell">
                        <span>{{$t('dashboard.now_rate')}}</span>
                      </div>
                    </th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(v,k) in inActive_workers" :key="k">
                    <td>
                      <div class="td-cell">
                        <span>{{v.last_share_time}}</span>
                      </div>
                    </td>
                    <td>
                      <div class="td-cell">
                        <span>{{v.worker_name}}</span>
                      </div>
                    </td>
                    <td>
                      <div class="td-cell">
                        <span>{{v.accept_15m}}</span>
                      </div>
                    </td>
                  </tr>
                  <tr v-if="!inActive_workers.length">
                    <td colspan="3">
                      <div class="td-cell">
                        <p>{{$t('unit.no_data')}}</p>
                      </div>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
        <!-- 底部列表 end -->
      </div>
    </div>
    <!-- 非全屏 end -->
  </div>
</template>
<script>
import {
  InWorkStats,
  InGetSubaccountAsset,
  InSetSubaccountAsset,
  InWorkerList,
  getWarning,
  InWorkerShare,
  InGetPaymentStas,
  InGetWorkerStas,
} from '@/api';
import Vue from 'vue';

import echarts from '@/components/Echarts';
import Breadcrumb from '@/components/Breadcrumb';
import Cu from '@/components/CountUp';
import Spinner from '@/components/Spinner';
// import subAccount from '@/components/SubAccount';
import screenfull from 'screenfull';
import moment from 'moment';
import { mapGetters, mapMutations } from 'vuex';
import {
  innovateSuanLiEchartsOption,
  suanLiFullEchartsOption,
} from './common/suanLiEchartsOption';
import {
  kuangJiEchartsOption,
  kuangJiFullEchartsOption,
} from './common/kuangJiEchartsOption';
import shouyiOption from './common/shouyiOption';

export default {
  name: 'innovate',
  components: {
    echarts,
    Breadcrumb,
    Cu,
    // subAccount,
    Spinner,
  },
  data() {
    return {
      timer: null,
      breadcrumbs: [
        {
          path: '/',
          titleKey: 'router.home',
        },
        {
          path: '/pools/dashboard',
          titleKey: 'router.dashboard',
        },
      ],
      shares_30m: 0,
      shares_30m_unit: '',
      shares_3h: 0,
      shares_3h_unit: '',
      shares_24h: 0,
      shares_24h_unit: '',
      sum_income: 0,
      pay_income: 0,
      net_income: 0,
      not_pay_income: 0,
      today_income: 0,
      getWarning_init: true,
      showWarningInfo: false,
      noMill: false,
      spinner_size: '.03125rem',
      asset: {
        unit: 'G',
        share: 0,
        worker_num: 0,
      },
      active_count: 0,
      dead_count: 0,
      inactive_count: 0,
      showData: true,
      active_workers: [],
      inActive_workers: [],
      suanLi_dimension: '1h',
      kuangji_dimension: '1h',
      suanLiEchartsOption: JSON.parse(
        JSON.stringify(innovateSuanLiEchartsOption),
      ),
      suanLiFullEchartsOption: JSON.parse(
        JSON.stringify(suanLiFullEchartsOption),
      ),
      shouyiOption: JSON.parse(JSON.stringify(shouyiOption)),
      kuangJiEchartsOption: JSON.parse(JSON.stringify(kuangJiEchartsOption)),
      kuangJiFullEchartsOption: JSON.parse(
        JSON.stringify(kuangJiFullEchartsOption),
      ),
      get_worker_stas_data: {
        active: [],
        inactive: [],
        time: [],
      },
      set_asset: {
        hash_rate: 0,
        unit: '',
        worker_num: 0,
      },
      paymentHistoryLimit: 30,

      showSubAccount: false,
      loading: {
        workStats_init_loading: true,
        workStats_loading: false,
        get_subaccount_asset_loading: false,
        activeWorkerList_loading: false,
        inActiveWorkerList_loading: false,

        set_subaccount_asset_share_loading: false,
        set_subaccount_asset_worker_loading: false,

        paymentHistory_init_loading: true,
        paymentHistory_loading: false,

        getWorkerStas_init_loading: true,
        getWorkerStas_loading: false,

        subaccountHistory_init_loading: true,
        subaccountHistory_loading: false,
      },

      suanli_is_setting: false,
      kuangji_is_setting: false,

      subaccount_history_time: [],
      subaccount_history_share: [],
      subaccount_history_unit: '',

      baseUnit: {
        H: 1,
        HH: 1,
        KH: 10 ** 3,
        MH: 10 ** 6,
        GH: 10 ** 9,
        TH: 10 ** 12,
        PH: 10 ** 15,
      },
    };
  },
  computed: {
    ...mapGetters([
      'subCoinType',
      'subAddress',
      'subId',
      'subCuid',
      'id',
      'obAccessKey',
      'language',
    ]),
    suanli_unit_list() {
      let obj = {};
      if (this.subCoinType === 'zec') {
        obj = {
          K: 1 / (10 ** 6),
          M: 1 / (10 ** 3),
          G: 1,
          T: 10 ** 3,
          P: 10 ** 6,
          E: 10 ** 9,
        };
      } else {
        obj = {
          G: 1,
          T: 10 ** 3,
          P: 10 ** 6,
          E: 10 ** 9,
        };
      }
      return obj;
    },
    coinHashUnit() {
      return this.subCoinType === 'zec' ? 'Sol' : 'H';
    },
    incomeDecimal() {
      return this.subCoinType === 'eth' ? 9 : 8;
    },
    coin_type_up() {
      return this.subCoinType.toUpperCase();
    },
    tableValueFormatParm() {
      if (this.subCoinType === 'eth') {
        return 10 ** 9;
      }
      return 10 ** 8;
    },
    hasIncome() {
      return parseFloat(this.sum_income) || 0;
    },
    isFullscreen: {
      get() {
        return this.$store.getters.isFullscreen;
      },
      set(val) {
        this.SET_IS_FULLSCREEN(val);
      },
    },
    subaccount_history_current_share() {
      return this.subaccount_history_share.map((v) => {
        const share =
          (v * this.baseUnit[`${this.subaccount_history_unit}H`]) /
          this.baseUnit[`${this.asset.unit}H`];
        return (Math.floor(share * 100) / 100).toFixed(2);
      });
    },
    preHelpHref() {
      return `https://support.dpool.top/hc/${this.language === 'zh' ? 'zh-cn' : 'en-us'}`;
    },
    helpHref() {
      switch (this.subCoinType) {
        case 'eth':
          return `${this.preHelpHref}/articles/360015785251`;
        case 'dcr':
          return `${this.preHelpHref}/articles/360015589852`;
        case 'etp':
          return `${this.preHelpHref}/articles/360015589972`;
        case 'zec':
          return `${this.preHelpHref}/articles/360019801832`;
        default:
          return '';
      }
    },
  },
  created() {
    if (screenfull.enabled) {
      screenfull.on('change', this.screenChangehandler);
    }
    this.getSubaccountAsset();
    this.getInWorkStats();
    this.getWorkerList();
    this.timer = setInterval(() => {
      this.getInWorkStats();
      this.getWorkerList();
      this.getInWorkerShare();
      this.getInGetPaymentStas();
      this.getInGetWorkerStas();
    }, 15000);
  },
  beforeDestroy() {
    this.isFullscreen = false;
    this.exitFullScreen();
    screenfull.off('change', this.screenChangehandler);
    clearInterval(this.timer);
  },
  methods: {
    ...mapMutations(['SET_IS_FULLSCREEN']),
    toggleEchartsLang() {
      this.kuangJiEchartsOption.legend.data = [this.$t('dashboard.active_minging_mashine_number'), this.$t('dashboard.mining_machine_assets')];
      this.kuangJiEchartsOption.yAxis[0].name = this.$t('dashboard.machine_number');
      this.kuangJiEchartsOption.series[0].name = this.$t('dashboard.active_minging_mashine_number');
      this.kuangJiEchartsOption.series[1].name = this.$t('dashboard.mining_machine_assets');

      if (this.$refs.kuangji_noFull_echarts) {
        this.$refs.kuangji_noFull_echarts.setOption(this.kuangJiEchartsOption);
      }

      this.kuangJiFullEchartsOption.legend.data = [this.$t('dashboard.active_minging_mashine_number'), this.$t('dashboard.mining_machine_assets')];
      this.kuangJiFullEchartsOption.yAxis[0].name = this.$t('dashboard.machine_number');
      this.kuangJiFullEchartsOption.series[0].name = this.$t('dashboard.active_minging_mashine_number');
      this.kuangJiFullEchartsOption.series[1].name = this.$t('dashboard.mining_machine_assets');

      if (this.$refs.kuangji_full_echarts) {
        this.$refs.kuangji_full_echarts.setOption(this.kuangJiFullEchartsOption);
      }

      this.shouyiOption.legend.data = [this.$t('dashboard.income')];
      this.shouyiOption.yAxis.name = this.$t('dashboard.income');
      this.shouyiOption.series[0].name = this.$t('dashboard.income');

      if (this.$refs['shouyi-echarts']) {
        this.$refs['shouyi-echarts'].setOption(this.shouyiOption);
      }

      this.suanLiEchartsOption.legend.data = [this.$t('dashboard.rate'), this.$t('dashboard.hash_rate')];
      this.suanLiEchartsOption.yAxis[0].name = this.$t('dashboard.rate');
      this.suanLiEchartsOption.series[0].name = this.$t('dashboard.rate');
      this.suanLiEchartsOption.series[1].name = this.$t('dashboard.hash_rate');

      if (this.$refs.suanli_noFull_echarts) {
        this.$refs.suanli_noFull_echarts.setOption(this.suanLiEchartsOption);
      }

      this.suanLiFullEchartsOption.legend.data = [this.$t('dashboard.rate'), this.$t('dashboard.hash_rate')];
      this.suanLiFullEchartsOption.yAxis[0].name = this.$t('dashboard.rate');
      this.suanLiFullEchartsOption.series[0].name = this.$t('dashboard.rate');
      this.suanLiFullEchartsOption.series[1].name = this.$t('dashboard.hash_rate');

      if (this.$refs.suanli_full_echarts) {
        this.$refs.suanli_full_echarts.setOption(this.suanLiFullEchartsOption);
      }
    },
    getInWorkStats() {
      if (this.loading.workStats_loading) {
        return;
      }
      this.loading.workStats_loading = true;
      InWorkStats({
        coin_type: this.subCoinType,
        address: this.subAddress,
      })
        .then((res) => {
          if (res.data.status === 1) {
            const data = res.data.data;
            const accept = data.share_accept;
            const accept3h = data.share_accept_h;
            const accept24h = data.share_accept_d || 0;

            const a = Vue.filter('formatHashrate')(accept).split(' ');
            const a3h = Vue.filter('formatHashrate')(accept3h).split(' ');
            const a24h = Vue.filter('formatHashrate')(accept24h).split(' ');
            this.shares_30m = a[0];
            this.shares_30m_unit = `${a[1]}${this.coinHashUnit}`;
            this.shares_3h = a3h[0];
            this.shares_3h_unit = `${a3h[1]}${this.coinHashUnit}`;
            this.shares_24h = a24h[0];
            this.shares_24h_unit = `${a24h[1]}${this.coinHashUnit}`;
            // 有15m算力，且没有算力预警
            if (Number(this.shares_15m)) {
              this.getWarning();
            }
            this.sum_income = this.tableValueFormat(data.sum_income);
            this.pay_income = this.tableValueFormat(data.pay_income);
            this.net_income = this.tableValueFormat(data.net_income);
            this.today_income = this.tableValueFormat(data.today_income);
            this.not_pay_income = this.tableValueFormat(data.not_pay_income);
            this.active_count = data.active_count;
            this.dead_count = data.dead_count;
            this.inactive_count = data.inactive_count;
            this.noMill = (data.active_count + data.dead_count + data.inactive_count) === 0;
          } else {
            this.shares_30m = 0;
            this.shares_30m_unit = this.coinHashUnit;
            this.shares_3h = 0;
            this.shares_3h_unit = this.coinHashUnit;
            this.shares_24h = 0;
            this.shares_24h_unit = this.coinHashUnit;
            this.sum_income = 0;
            this.pay_income = 0;
            this.net_income = 0;
            this.today_income = 0;
            this.not_pay_income = 0;
            this.active_count = 0;
            this.dead_count = 0;
            this.inactive_count = 0;
            this.noMill = false;
          }
          this.loading.workStats_init_loading = false;
          this.loading.workStats_loading = false;
        })
        .catch(() => {
          this.loading.workStats_init_loading = false;
          this.loading.workStats_loading = false;
        });
    },
    tableValueFormat(value) {
      return (value / this.tableValueFormatParm).toFixed(this.incomeDecimal);
    },
    toSetWarning() {
      this.$router.push('/subaccount?type=setwarning');
    },
    getWarning() {
      // 有15m算力，且没有算力预警
      if (!this.getWarning_init) {
        return;
      }
      this.getWarning_init = false;
      getWarning({
        cuid: this.subCuid,
        coin_type: this.subCoinType,
        config_id: this.subId,
      })
        .then((res) => {
          if (res.data.status === 1 && !res.data.data) {
            this.showWarningInfo = true;
          }
          this.getWarning_init = false;
        })
        .catch(() => {
          this.getWarning_init = true;
        });
    },
    getSubaccountAsset() {
      this.loading.get_subaccount_asset_loading = true;
      InGetSubaccountAsset({
        puid: this.subCuid,
        coin_type: this.subCoinType,
        config_id: this.subId,
      })
        .then((res) => {
          if (res.data.status === 1) {
            const data = res.data.data;
            if (Array.isArray(data) && !data.length) {
              [this.asset] = [
                {
                  unit: this.subCoinType === 'zec' ? 'K' : 'G',
                  share: 0,
                  worker_num: 0,
                },
              ];
            } else {
              [this.asset] = [data];
            }
          }
          this.loading.get_subaccount_asset_loading = false;
        })
        .catch(() => {
          this.loading.get_subaccount_asset_loading = false;
        });
    },
    setSubaccountAsset(type) {
      // type:1 矿机资产 2算力
      const params = {
        type,
        cuid: this.subCuid,
        uid: this.id,
        coin_type: this.subCoinType,
      };
      if (type === 1) {
        if (this.loading.set_subaccount_asset_worker_loading) {
          return;
        }
        Object.assign(params, { worker_num: this.set_asset.worker_num });
        this.loading.set_subaccount_asset_worker_loading = true;
      } else {
        if (this.loading.set_subaccount_asset_share_loading) {
          return;
        }
        Object.assign(params, {
          share: this.set_asset.hash_rate,
          unit: this.set_asset.unit,
        });
        this.loading.set_subaccount_asset_share_loading = true;
      }
      InSetSubaccountAsset(params)
        .then((res) => {
          if (res.data.status === 1) {
            this.$notify({
              message:
                type === 1
                  ? this.$t('dashboard.set_mining')
                  : this.$t('dashboard.set_hash_rate_success'),
              type: 'success',
              duration: 1000,
              showClose: false,
            });
            if (type === 1) {
              this.asset.worker_num = params.worker_num;
              this.kuangji_is_setting = false;
            } else {
              this.asset.unit = params.unit;
              this.asset.share = params.share;
              this.suanli_is_setting = false;
            }
          }
          this.loading.set_subaccount_asset_share_loading = false;
          this.loading.set_subaccount_asset_worker_loading = false;
        })
        .catch(() => {
          this.loading.set_subaccount_asset_share_loading = false;
          this.loading.set_subaccount_asset_worker_loading = false;
        });
    },
    getWorkerList() {
      if (this.subCoinType === 'eth' || this.subCoinType === 'etp') {
        if (this.loading.activeWorkerList_loading && this.loading.inActiveWorkerList_loading) {
          return;
        }
        this.loading.activeWorkerList_loading = true;
        this.loading.inActiveWorkerList_loading = true;
        InWorkerList({
          coin_type: this.subCoinType,
          address: this.subAddress,
        }).then((res) => {
          if (res.data.status === 1) {
            const activeList = [];
            const deadList = [];
            res.data.data.data.forEach((v) => {
              if (v.offline) {
                deadList.push(v);
              } else {
                activeList.push(v);
              }
            });
            const hashRate = (accept15m) => {
              const arr = accept15m.split(' ');
              return arr[0] * this.baseUnit[`${arr[1]}H`];
            };
            this.active_workers = activeList.sort((a, b) => hashRate(a.accept_15m) - hashRate(b.accept_15m),
            ).slice(0, 6);
            this.inActive_workers = deadList.sort((a, b) => hashRate(b.accept_15m) - hashRate(a.accept_15m),
            ).slice(0, 6);
          } else {
            this.active_workers = [];
            this.inActive_workers = [];
          }
          this.loading.activeWorkerList_loading = false;
          this.loading.inActiveWorkerList_loading = false;
        }).catch(() => {
          this.loading.activeWorkerList_loading = false;
          this.loading.inActiveWorkerList_loading = false;
        });
      } else {
        if (!this.loading.activeWorkerList_loading) {
          this.loading.activeWorkerList_loading = true;
          InWorkerList({
            coin_type: this.subCoinType,
            address: this.subAddress,
            page: 1,
            limit: 6,
            status: 'ACTIVE',
            order_by: 'accept_15m',
            sort: 'asc',
          }).then((res) => {
            if (res.data.status === 1) {
              this.active_workers = res.data.data.list;
            } else {
              this.active_workers = [];
            }
            this.loading.activeWorkerList_loading = false;
          }).catch(() => {
            this.loading.activeWorkerList_loading = false;
          });
        }
        if (!this.loading.inActiveWorkerList_loading) {
          this.loading.inActiveWorkerList_loading = true;
          InWorkerList({
            coin_type: this.subCoinType,
            address: this.subAddress,
            page: 1,
            limit: 6,
            status: 'INACTIVE',
            order_by: 'last_share_time',
            sort: 'desc',
          }).then((res) => {
            if (res.data.status === 1) {
              this.inActive_workers = res.data.data.list;
            } else {
              this.inActive_workers = [];
            }
            this.loading.inActiveWorkerList_loading = false;
          }).catch(() => {
            this.loading.inActiveWorkerList_loading = false;
          });
        }
      }
    },
    closeSetting() {
      if (!this.loading.set_subaccount_asset_worker_loading) {
        this.kuangji_is_setting = false;
      }
      if (!this.loading.set_subaccount_asset_share_loading) {
        this.suanli_is_setting = false;
      }
    },
    toFullScreen() {
      if (screenfull.enabled) {
        screenfull.request();
      } else {
        // 不支持全屏
        this.$message.error(this.$t('dashboard.no_support'));
      }
    },
    exitFullScreen() {
      if (screenfull.enabled) {
        screenfull.exit();
      }
    },
    screenChangehandler() {
      this.isFullscreen = screenfull.isFullscreen;
      if (this.isFullscreen) {
        this.$refs.suanli_full_echarts.chart.resize({
          height: 2.239583 * window.rem,
          width: 4.453125 * window.rem,
        });
        this.$refs.kuangji_full_echarts.chart.resize({
          height: 2.239583 * window.rem,
          width: 4.453125 * window.rem,
        });
      }
    },
    getInWorkerShare() {
      if (this.loading.subaccountHistory_loading) {
        return;
      }
      this.loading.subaccountHistory_loading = true;
      InWorkerShare({
        coin_type: this.subCoinType,
        address: this.subAddress,
        type: this.suanLi_dimension,
      }).then((res) => {
        const time = [];
        let unit = 'G';
        const shareAccept = [];
        if (res.data.status === 1 && res.data.data) {
          unit = res.data.unit.trim();
          res.data.data.forEach((v) => {
            time.push(v.time);
            shareAccept.push(v.share);
          });
        }
        this.subaccount_history_time = time;
        this.subaccount_history_share = shareAccept;
        this.subaccount_history_unit = unit;

        this.setSuanliEchartsOption(
          'suanLiEchartsOption',
          'suanli_noFull_echarts',
        );
        this.setSuanliEchartsOption(
          'suanLiFullEchartsOption',
          'suanli_full_echarts',
        );
        this.loading.subaccountHistory_init_loading = false;
        this.loading.subaccountHistory_loading = false;
      }).catch(() => {
        this.loading.subaccountHistory_init_loading = false;
        this.loading.subaccountHistory_loading = false;
      });
    },
    getInGetPaymentStas() {
      if (this.loading.paymentHistory_loading) {
        return;
      }
      this.loading.paymentHistory_loading = true;
      InGetPaymentStas({
        coin_type: this.subCoinType,
        address: this.subAddress,
        limit: this.paymentHistoryLimit,
      })
        .then((res) => {
          const xData = [];
          const seriesData = [];
          if (res.data.status === 1 && res.data.data) {
            res.data.data.reverse().forEach((v) => {
              xData.push(moment(v.time * 1000).format('YYYY-MM-DD'));
              seriesData.push(v.pay_amount / this.tableValueFormatParm);
            });
          }
          this.shouyiOption.xAxis.data = xData;
          this.shouyiOption.series[0].data = seriesData;
          this.shouyiOption.tooltip.formatter = (v) => {
            const arr = v.filter(item => item.axisDim === 'x');
            return `${this.$t('dashboard.time')}：${
              arr[0].name
            }<br/>${this.$t('dashboard.income')}：${arr[0].value}  ${
              this.coin_type_up
            }`;
          };
          this.$refs['shouyi-echarts'].setOption(this.shouyiOption);
          this.loading.paymentHistory_loading = false;
          this.loading.paymentHistory_init_loading = false;
        })
        .catch(() => {
          this.loading.paymentHistory_loading = false;
          this.loading.paymentHistory_init_loading = false;
        });
    },
    getInGetWorkerStas() {
      if (this.loading.getWorkerStas_loading) {
        return;
      }
      this.loading.getWorkerStas_loading = true;
      InGetWorkerStas({
        coin_type: this.subCoinType,
        address: this.subAddress,
        type: this.kuangji_dimension,
      })
        .then((res) => {
          const time = [];
          const active = [];
          const inactive = [];
          if (res.data.status === 1 && res.data.data) {
            res.data.data.forEach((v) => {
              time.push(v.time);
              active.push(v.workersOnline);
              inactive.push(this.asset.worker_num);
            });
          }
          this.get_worker_stas_data = {
            time,
            active,
            inactive,
          };
          this.setKuangJiEchartsOption(
            'kuangJiEchartsOption',
            'kuangji_noFull_echarts',
          );
          this.setKuangJiEchartsOption(
            'kuangJiFullEchartsOption',
            'kuangji_full_echarts',
          );
          this.loading.getWorkerStas_init_loading = false;
          this.loading.getWorkerStas_loading = false;
        })
        .catch(() => {
          this.loading.getWorkerStas_init_loading = false;
          this.loading.getWorkerStas_loading = false;
        });
    },
    setKuangJiEchartsOption(optionName, echartsName) {
      this[optionName].xAxis.data = this.get_worker_stas_data.time;
      this[optionName].series[0].data = this.get_worker_stas_data.active;
      this[optionName].series[1].data = this.get_worker_stas_data.inactive;
      this[optionName].tooltip.formatter = (v) => {
        let str = '';
        v.filter(item => item.axisDim === 'x').forEach((item, index) => {
          if (!index) {
            str += `${this.$t('dashboard.time')}：${moment(
              item.axisValue * 1000,
            ).format(this.kuangji_dimension === '1h' ? 'YYYY-MM-DD HH:mm' : 'YYYY-MM-DD')}`;
          }
          if (item.color === '#70c1b3') {
            str += `<br/><i style="background:${
              item.color
            };display:inline-block;height:12px;width:12px;border-radius:6px;"></i> ${this.$t(
              'dashboard.active_minging_mashine_number',
            )}：${item.data}`;
          }
          if (item.color === '#ccc') {
            str += `<br/><i style="background:${
              item.color
            };display:inline-block;height:12px;width:12px;border-radius:6px;"></i> ${this.$t(
              'dashboard.mining_machine_assets',
            )}：${item.data}`;
          }
        });
        return str;
      };
      this[optionName].xAxis.axisLabel.formatter = (value) => {
        const formatterTime = moment(value * 1000).format(
          this.kuangji_dimension === '1h' ? 'HH:mm YYYY-MM-DD' : 'YYYY-MM-DD',
        );
        return formatterTime.split(' ').join('\n');
      };
      if (this.$refs[echartsName]) {
        this.$refs[echartsName].setOption(this[optionName]);
      }
    },
    setSuanliEchartsOption(optionName, echartsName) {
      this[optionName].xAxis.data = this.subaccount_history_time;
      this[optionName].yAxis[0].name = `${this.$t('dashboard.rate')}(${
        this.asset.unit
      }${this.coinHashUnit}/s)`;
      this[optionName].series[0].data = this.subaccount_history_current_share;
      this[optionName].series[1].data = new Array(
        this.subaccount_history_current_share.length,
      ).fill(this.asset.share);
      this[optionName].tooltip.formatter = (v) => {
        let str = '';
        v.filter(item => item.axisDim === 'x').forEach((item, index) => {
          if (!index) {
            str = `${this.$t('dashboard.time')}：${moment(
              item.axisValue * 1000,
            ).format(this.suanLi_dimension === '1h' ? 'YYYY-MM-DD HH:mm' : 'YYYY-MM-DD')}`;
          }
          if (item.color === '#70c1b3') {
            str += `<br/><i style="background:${
              item.color
            };display:inline-block;height:12px;width:12px;border-radius:6px;"></i> ${this.$t(
              'dashboard.rate',
            )}：${item.data}(${this.asset.unit}${this.coinHashUnit}/s)`;
          }
          if (item.color === '#ccc') {
            str += `<br/><i style="background:${
              item.color
            };display:inline-block;height:12px;width:12px;border-radius:6px;"></i> ${this.$t(
              'dashboard.hash_rate',
            )}：${item.data}(${this.asset.unit}${this.coinHashUnit}/s)`;
          }
        });
        return str;
      };
      this[optionName].xAxis.axisLabel.formatter = (value) => {
        const formatterTime = moment(value * 1000).format(
          this.suanLi_dimension === '1h' ? 'HH:mm YYYY-MM-DD' : 'YYYY-MM-DD',
        );
        return formatterTime.split(' ').join('\n');
      };
      if (this.$refs[echartsName]) {
        this.$refs[echartsName].setOption(this[optionName]);
      }
    },
  },
  watch: {
    'set_asset.hash_rate': {
      handler(val) {
        let v = val.toString();
        v = v.replace(/[^\d.]/g, '');
        if (v < 0) {
          v = '0';
        }
        if (v > 10000) {
          v = '10000';
        }
        let arr = v.split('.');
        if (arr.length > 2) {
          v = `${arr[0]}.${arr[1]}`;
          arr = v.split('.');
        }
        if (arr[1] && arr[1].length > 2) {
          v = `${arr[0]}.${arr[1][0]}${arr[1][1]}`;
        }
        this.set_asset.hash_rate = v;
      },
    },
    'set_asset.worker_num': {
      handler(val) {
        let v = val.toString();
        v = v.replace(/[^\d]/g, '');
        if (v < 0) {
          v = '0';
        }
        if (v > 200000) {
          v = '200000';
        }
        this.set_asset.worker_num = v;
      },
    },
    'asset.unit': {
      handler() {
        this.setSuanliEchartsOption(
          'suanLiEchartsOption',
          'suanli_noFull_echarts',
        );
        this.setSuanliEchartsOption(
          'suanLiFullEchartsOption',
          'suanli_full_echarts',
        );
      },
    },
    'asset.share': {
      handler() {
        this.setSuanliEchartsOption(
          'suanLiEchartsOption',
          'suanli_noFull_echarts',
        );
        this.setSuanliEchartsOption(
          'suanLiFullEchartsOption',
          'suanli_full_echarts',
        );
      },
    },
    'asset.worker_num': {
      handler() {
        this.getInGetWorkerStas();
      },
    },
    subId() {
      // 矿机资产  理论算力
      this.getSubaccountAsset();
      // 获取算力预警
      this.showWarningInfo = false;
      this.getWarning_init = true;
      this.loading.workStats_init_loading = true;
      // 实时算力
      this.getInWorkStats();
      this.loading.subaccountHistory_init_loading = true;
      // 算力图
      this.getInWorkerShare();
      this.loading.paymentHistory_init_loading = true;
      // 收益图
      this.getInGetPaymentStas();
      this.loading.getWorkerStas_init_loading = true;
      // 矿机图
      this.getInGetWorkerStas();

      this.getWorkerList();
    },
    paymentHistoryLimit: {
      handler() {
        this.getInGetPaymentStas();
      },
      immediate: true,
    },
    suanLi_dimension: {
      handler() {
        this.getInWorkerShare();
      },
      immediate: true,
    },
    kuangji_dimension: {
      handler() {
        this.getInGetWorkerStas();
      },
      immediate: true,
    },
    language: {
      handler() {
        this.toggleEchartsLang();
      },
      immediate: true,
    },
  },
};
</script>
